package filter;

import java.awt.image.BufferedImage;

public class Raster{
	protected int width;
	protected int height;
	
	protected short r[][];
	protected short g[][];
	protected short b[][];
	protected short a[][];
	
	public Raster( int width, int height ){
		r = new short[ ( height + 2 ) ][ ( width + 2 ) ];
		g = new short[ ( height + 2 ) ][ ( width + 2 ) ];
		b = new short[ ( height + 2 ) ][ ( width + 2 ) ];
		a = new short[ ( height + 2 ) ][ ( width + 2 ) ];
	}
	
	public Raster( BufferedImage src ){
		width = src.getWidth();
		height = src.getHeight();
		
		// add 2 for operational convenience
		r = new short[ ( height + 2 ) ][ ( width + 2 ) ];
		g = new short[ ( height + 2 ) ][ ( width + 2 ) ];
		b = new short[ ( height + 2 ) ][ ( width + 2 ) ];
		a = new short[ ( height + 2 ) ][ ( width + 2 ) ];
		
		// fill 0 for edge
		for( int i = 0; i < height + 2; i++ ){
			r[ i ][ 0 ] = 0;	r[ i ][ width + 1 ] = 0;
			g[ i ][ 0 ] = 0;	g[ i ][ width + 1 ] = 0;
			b[ i ][ 0 ] = 0;	b[ i ][ width + 1 ] = 0;
			a[ i ][ 0 ] = 255;	a[ i ][ width + 1 ] = 255;
		}
		for( int i = 0; i < width + 2; i++ ){
			r[ 0 ][ i ] = 0;	r[ height + 1 ][ i ] = 0;
			g[ 0 ][ i ] = 0;	g[ height + 1 ][ i ] = 0;
			b[ 0 ][ i ] = 0;	b[ height + 1 ][ i ] = 0;
			a[ 0 ][ i ] = 255;	a[ height + 1 ][ i ] = 255;
		}
		// file image pixels
		for( int i = 1; i < height + 1; i++ ){
			for( int j = 1; j < width + 1; j++ ){
				int src_x = j - 1;	int src_y = i - 1;
				int rgb = src.getRGB( src_x, src_y );
				
				r[ i ][ j ] = ( short )( ( 0x00FF0000 & rgb ) >> 16 );
				g[ i ][ j ] = ( short )( ( 0x0000FF00 & rgb ) >> 8 );
				b[ i ][ j ] = ( short )( 0x000000FF & rgb );
				a[ i ][ j ] = ( short )( 0x000000FF & ( rgb >> 24 ) );
			}
		}
	}

	public BufferedImage get_image( int type ){
		BufferedImage output = new BufferedImage( width, height, type );
		
		for( int i = 1; i < height + 1; i++ ){
			for( int j = 1; j < width + 1; j++ ){
				int r = ( ( int )this.r[ i ][ j ] << 16 ) & 0x00FF0000;
				int g = ( ( int )this.g[ i ][ j ] << 8 ) & 0x0000FF00;
				int b = ( int )this.b[ i ][ j ] & 0x000000FF;
				int a = ( ( int )this.a[ i ][ j ] << 24 ) & 0xFF000000;
				
				int rgb = r | g | b | a;
				int output_x = j - 1;	int output_y = i - 1;
				output.setRGB( output_x, output_y, rgb );
			}
		}
		
		return output;
	}
}